﻿using BPMN.Domain;
using BPMN.Domain.Interface;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using BPMN.Domain.Entity.SysDictonary;
using AutoMapper;
using BPMN.DomianShare.PulicDto;

namespace BPMN.Infrastructure.Repository
{
    public class RepositoryBase<T> : IRepositoryBase<T> where T : class
    {
        /// <summary>
        /// 定义事务全局变量
        /// </summary>
        private IDbContextTransaction tran;
        public IDapper IDapper;
        private readonly MyDbContext db;
        public RepositoryBase(MyDbContext db, IDapper IDapper)
        {
            this.IDapper = IDapper;
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Add(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await SaveChange();
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<int> AddRange(List<T> list)
        {
            await db.Set<T>().AddRangeAsync(list);
            return await SaveChange();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<int> RealDel(IEnumerable<T> list)
        {
            await Task.Run(async () => db.Set<T>().RemoveRange(list));

            return await SaveChange();
        }
        /// <summary>
        /// 逻辑删除（单删）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<int> Delete(int Id)
        {
            var slist = await db.Set<T>().FindAsync(Id);
            if (slist != null)
            {
                db.Entry(slist).Property("IsDel").IsModified = true;
                db.Entry(slist).Property("IsDel").CurrentValue = false;
            }
            return await SaveChange();
        }
        /// <summary>
        /// 单删除（真删）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<int> RealDeleteOne(int Id)
        {
            var slist = await db.Set<T>().FindAsync(Id);
            if (slist != null)
            {
                await Task.Run(() => db.Set<T>().Remove(slist));
            }
            return await SaveChange();
        }
        /// <summary>
        /// 根据Id查询
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<T> Get(int Id)
        {
            return await db.Set<T>().FindAsync(Id);
        }
        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<T>> GetAll()
        {
            return await Task.Run(async () => db.Set<T>());
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetListPage(int PageIndex, int PageSize)
        {
            var query = db.Set<T>();
            var TotalCount = query.CountAsync();
            var PageCount = (int)Math.Ceiling(TotalCount.Result * 1.0 / PageSize);
            var slist = await query.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToListAsync();
            return new { TotalCount = TotalCount, PageCount = PageCount, slist = slist };
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        public async Task<int> SaveChange()
        {
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {

            await Task.Run(async () => db.Set<T>().Update(entity));
            return await SaveChange();
        }
        /// <summary>
        /// 开启事务
        /// </summary>
        public void BeginTran()
        {
            tran = db.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTran()
        {
            tran.Commit();
        }
        /// <summary>
        /// 事务回滚
        /// </summary>
        public void RollBackTran()
        {
            tran.Rollback();
        }

        public async Task<List<PulicDictonaryListResponseDto>> ExecSqlDictionary(string sql)
        {
            var maxdts = await Task.Run(() => IDapper.QueryList<PulicDictonaryListResponseDto>(sql, null));
            return maxdts;
        }

        //public Task<IQueryable<T>> ExecSql(string sql)
        //{
        //   return db.Database.f
        //}
    }
}
